<!DOCTYPE html>












  


<html class="theme-next mist use-motion" lang="en">
<head>
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=2">
<meta name="theme-color" content="#222">






  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.3.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/imagesfavicon.ico?v=6.3.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/imagesfavicon.ico?v=6.3.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.3.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '6.3.0',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>
  <meta name="description" content="引言这篇记载一下 Python 环境下使用 matplotlib 绘制各种曲线图的用法，阅读这篇文章你将会获得如下内容：  matplotlib 及环境配置。 一幅数据绘图的结构都是如何组成的，与 matplotlib 相关的名称是如何对应的？ 常见的数据绘图都包含哪些，以及是如何绘制的？  你可能需要的先前技能如下：  Python 开发环境及 matplotlib 工具包 Python 基础语">
<meta name="keywords" content="Python">
<meta property="og:type" content="article">
<meta property="og:title" content="Python matplotlib 数据可视化">
<meta property="og:url" content="https://absentm.github.io/2017/03/18/Python-matplotlib-数据可视化/index.html">
<meta property="og:site_name" content="AbsentM&#39;s Notes">
<meta property="og:description" content="引言这篇记载一下 Python 环境下使用 matplotlib 绘制各种曲线图的用法，阅读这篇文章你将会获得如下内容：  matplotlib 及环境配置。 一幅数据绘图的结构都是如何组成的，与 matplotlib 相关的名称是如何对应的？ 常见的数据绘图都包含哪些，以及是如何绘制的？  你可能需要的先前技能如下：  Python 开发环境及 matplotlib 工具包 Python 基础语">
<meta property="og:locale" content="en">
<meta property="og:image" content="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/Python_Figure_Structure.png">
<meta property="og:image" content="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/figure.png">
<meta property="og:image" content="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/colormaps.png">
<meta property="og:image" content="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/line_style.png">
<meta property="og:image" content="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/marks.png">
<meta property="og:image" content="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/legend.png">
<meta property="og:image" content="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/bar.png">
<meta property="og:updated_time" content="2019-07-22T11:08:56.908Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python matplotlib 数据可视化">
<meta name="twitter:description" content="引言这篇记载一下 Python 环境下使用 matplotlib 绘制各种曲线图的用法，阅读这篇文章你将会获得如下内容：  matplotlib 及环境配置。 一幅数据绘图的结构都是如何组成的，与 matplotlib 相关的名称是如何对应的？ 常见的数据绘图都包含哪些，以及是如何绘制的？  你可能需要的先前技能如下：  Python 开发环境及 matplotlib 工具包 Python 基础语">
<meta name="twitter:image" content="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/Python_Figure_Structure.png">






  <link rel="canonical" href="https://absentm.github.io/2017/03/18/Python-matplotlib-数据可视化/">



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Python matplotlib 数据可视化 | AbsentM's Notes</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?021d64369b3c401c47c6ab7aa56f7074";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">AbsentM's Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="Toggle navigation bar">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br>Home</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br>Categories</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>Archives</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>Tags</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br>About</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>Search</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="Searching..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  
    <div class="reading-progress-bar"></div>
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://absentm.github.io/2017/03/18/Python-matplotlib-数据可视化/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="AbsentM">
      <meta itemprop="description" content="Avenue to Jane!">
      <meta itemprop="image" content="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/googlrPhoto.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="AbsentM's Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Python matplotlib 数据可视化
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              

              
                
              

              <time title="Created: 2017-03-18 15:59:30" itemprop="dateCreated datePublished" datetime="2017-03-18T15:59:30+08:00">2017-03-18</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Edited on</span>
                
                <time title="Modified: 2019-07-22 19:08:56" itemprop="dateModified" datetime="2019-07-22T19:08:56+08:00">2019-07-22</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Python-Notes/" itemprop="url" rel="index"><span itemprop="name">Python Notes</span></a></span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2017/03/18/Python-matplotlib-数据可视化/#comments" itemprop="discussionUrl">
                
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2017/03/18/Python-matplotlib-数据可视化/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2017/03/18/Python-matplotlib-数据可视化/" class="leancloud_visitors" data-flag-title="Python matplotlib 数据可视化">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">Views: </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="引言"><a href="#引言" class="headerlink" title="引言"></a>引言</h2><p>这篇记载一下 Python 环境下使用 matplotlib 绘制各种曲线图的用法，阅读这篇文章你将会获得如下内容：</p>
<ul>
<li>matplotlib 及环境配置。</li>
<li>一幅数据绘图的结构都是如何组成的，与 matplotlib 相关的名称是如何对应的？</li>
<li>常见的数据绘图都包含哪些，以及是如何绘制的？</li>
</ul>
<p>你可能需要的先前技能如下：</p>
<ul>
<li>Python 开发环境及 matplotlib 工具包</li>
<li>Python 基础语法</li>
<li>Python numpy 包使用</li>
</ul>
<hr>
<h2 id="matplotlib-安装配置"><a href="#matplotlib-安装配置" class="headerlink" title="matplotlib 安装配置"></a>matplotlib 安装配置</h2><p>使用 Python 进行数据绘图前，Python 环境的安装配置是必须，请参看这篇文章：<br><a href="https://absentm.github.io/2015/12/02/python%E5%AE%89%E8%A3%85%E7%AE%80%E8%AE%B0/">Python 环境安装配置</a>。</p>
<p>在各种环境中 (Windows、Linux、Mac) 的 matplotlib 环境安装配置如下： (以 Ubuntu 为例)</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 推荐使用这种方式安装</span></span><br><span class="line"><span class="comment"># 安装 numpy、scipy包</span></span><br><span class="line">sudo apt-get install python-numpy</span><br><span class="line">sudo apt-get install python-scipy</span><br><span class="line"></span><br><span class="line"><span class="comment"># 安装 matplotlib 包</span></span><br><span class="line">sudo apt-get install python-matplotlib</span><br></pre></td></tr></table></figure>
<p>当然也可以使用 pip 安装：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">sudo pip install numpy</span><br><span class="line">sudo pip install scipy</span><br><span class="line">sudo pip install matplotlib</span><br></pre></td></tr></table></figure>
<hr>
<h2 id="图的基本结构"><a href="#图的基本结构" class="headerlink" title="图的基本结构"></a>图的基本结构</h2><p>通常，使用 numpy 组织数据, 使用 matplotlib API 进行数据图像绘制。 一幅数据图基本上包括如下结构：</p>
<ol>
<li>Data: 数据区，包括数据点、描绘形状</li>
<li>Axis: 坐标轴，包括 X 轴、 Y 轴及其标签、刻度尺及其标签</li>
<li>Title: 标题，数据图的描述</li>
<li>Legend: 图例，区分图中包含的多种曲线或不同分类的数据</li>
<li>其他的还有图形文本 (Text)、注解 (Annotate)等其他描述</li>
</ol>
<p>详细的结构图如下图所示：</p>
<p><img src="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/Python_Figure_Structure.png" alt="数据绘图基本结构"></p>
<p>This figure powered by <a href="https://www.snipaste.com/" target="_blank" rel="noopener">Snipaste</a> .</p>
<hr>
<h2 id="绘图分类"><a href="#绘图分类" class="headerlink" title="绘图分类"></a>绘图分类</h2><p>Matplotlib API 中提供了常见的绘图类型，常用的包括如下：</p>
<ul>
<li>常规图：regular plot</li>
<li>直方图：bar plot</li>
<li>散点图：scatter plot</li>
<li>饼状图：pie plot</li>
<li>轮廓图：contour plot</li>
<li>3D图：3D plot</li>
<li>多子图：subplot</li>
<li>显示图片：imshow</li>
</ul>
<p>参考文献 [3] 详细记录了 API 中的各种类型图的参数说明，不再一一赘述。</p>
<hr>
<h2 id="画法"><a href="#画法" class="headerlink" title="画法"></a>画法</h2><p>本篇以常规图为例，详细记录作图流程及技巧。按照绘图结构，可将数据图的绘制分为如下几个步骤：</p>
<ul>
<li>导入 matplotlib 包相关工具包</li>
<li>准备数据，numpy 数组存储</li>
<li>绘制原始曲线</li>
<li>配置标题、坐标轴、刻度、图例</li>
<li>添加文字说明、注解</li>
<li>显示、保存绘图结果</li>
</ul>
<p>先给出一个完整的图结构吧，这个图主要是绘制 cos、sin、sqrt 函数图像，如下：</p>
<p><img src="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/figure.png" alt="完整的常规图绘制结果"></p>
<h3 id="导包"><a href="#导包" class="headerlink" title="导包"></a>导包</h3><p>涉及到 matplotlib.pyplot、pylab 和 numpy，如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#coding:utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"><span class="keyword">from</span> pylab <span class="keyword">import</span> *</span><br></pre></td></tr></table></figure>
<h3 id="准备数据"><a href="#准备数据" class="headerlink" title="准备数据"></a>准备数据</h3><p>numpy 常用来组织源数据:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 定义数据部分</span></span><br><span class="line">x = np.arange(<span class="number">0.</span>, <span class="number">10</span>, <span class="number">0.2</span>)</span><br><span class="line">y1 = np.cos(x)</span><br><span class="line">y2 = np.sin(x)</span><br><span class="line">y3 = np.sqrt(x)</span><br></pre></td></tr></table></figure>
<h3 id="绘制基本曲线"><a href="#绘制基本曲线" class="headerlink" title="绘制基本曲线"></a>绘制基本曲线</h3><p>使用 plot 函数直接绘制上述函数曲线，可以通过配置 plot 函数参数调整曲线的样式、粗细、颜色、标记等：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 绘制 3 条函数曲线</span></span><br><span class="line">plt.plot(x, y1, color=<span class="string">'blue'</span>, linewidth=<span class="number">1.5</span>, linestyle=<span class="string">'-'</span>, marker=<span class="string">'.'</span>, label=<span class="string">r'$y = cos&#123;x&#125;$'</span>)</span><br><span class="line"></span><br><span class="line">plt.plot(x, y2, color=<span class="string">'green'</span>, linewidth=<span class="number">1.5</span>, linestyle=<span class="string">'-'</span>, marker=<span class="string">'*'</span>, label=<span class="string">r'$y = sin&#123;x&#125;$'</span>)</span><br><span class="line"></span><br><span class="line">plt.plot(x, y3, color=<span class="string">'m'</span>, linewidth=<span class="number">1.5</span>, linestyle=<span class="string">'-'</span>, marker=<span class="string">'x'</span>, label=<span class="string">r'$y = \sqrt&#123;x&#125;$'</span>)</span><br></pre></td></tr></table></figure>
<p><strong>1&gt; color 参数</strong></p>
<p>包含基本的红(red, r)、绿(green, g)、蓝(blue, b)、黑(k)、青色(c)、洋红色(m)、黄色(y)、白色(w)及其衍生色，还可以使用 6 个 16 进制数表示（如，’#FF00CC’, ‘#ff00ff’）。</p>
<p><img src="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/colormaps.png" alt="color 样式图"></p>
<p>color 参数图片由参考文献 [1] 提供。</p>
<p><strong>2&gt; linestyle 参数</strong></p>
<p>其中，linestyle 参数主要包含虚线、点化虚线、粗虚线、实线，表示符号见下图：</p>
<p><img src="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/line_style.png" alt="linestyle 参数"></p>
<p>linestyle 参数图片由参考文献 [1] 提供。</p>
<p><strong>3&gt; marker 参数</strong></p>
<p>在曲线上标记特殊的符号，以区分不同的线段，比较实用。常见的形状及表示符号如下图所示：</p>
<p><img src="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/marks.png" alt="marker 样式图"></p>
<p>marker 参数图片由参考文献 [1] 提供。</p>
<h3 id="设置坐标轴"><a href="#设置坐标轴" class="headerlink" title="设置坐标轴"></a>设置坐标轴</h3><p>可通过如下代码，移动坐标轴 <strong>spines</strong>，解说详见注释：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 坐标轴上移</span></span><br><span class="line">ax = plt.subplot(<span class="number">111</span>)</span><br><span class="line">ax.spines[<span class="string">'right'</span>].set_color(<span class="string">'none'</span>)     <span class="comment"># 去掉右边的边框线</span></span><br><span class="line">ax.spines[<span class="string">'top'</span>].set_color(<span class="string">'none'</span>)       <span class="comment"># 去掉上边的边框线</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 移动下边边框线，相当于移动 X 轴</span></span><br><span class="line">ax.xaxis.set_ticks_position(<span class="string">'bottom'</span>)    </span><br><span class="line">ax.spines[<span class="string">'bottom'</span>].set_position((<span class="string">'data'</span>, <span class="number">0</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 移动左边边框线，相当于移动 y 轴</span></span><br><span class="line">ax.yaxis.set_ticks_position(<span class="string">'left'</span>)</span><br><span class="line">ax.spines[<span class="string">'left'</span>].set_position((<span class="string">'data'</span>, <span class="number">0</span>))</span><br></pre></td></tr></table></figure>
<p>可通过如下代码，设置刻度尺间隔 <strong>lim</strong>、刻度标签 <strong>ticks</strong>：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 设置 x, y 轴的刻度取值范围</span></span><br><span class="line">plt.xlim(x.min()*<span class="number">1.1</span>, x.max()*<span class="number">1.1</span>)</span><br><span class="line">plt.ylim(<span class="number">-1.5</span>, <span class="number">4.0</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 设置 x, y 轴的刻度标签值</span></span><br><span class="line">plt.xticks([<span class="number">2</span>, <span class="number">4</span>, <span class="number">6</span>, <span class="number">8</span>, <span class="number">10</span>], [<span class="string">r'2'</span>, <span class="string">r'4'</span>, <span class="string">r'6'</span>, <span class="string">r'8'</span>, <span class="string">r'10'</span>])</span><br><span class="line">plt.yticks([<span class="number">-1.0</span>, <span class="number">0.0</span>, <span class="number">1.0</span>, <span class="number">2.0</span>, <span class="number">3.0</span>, <span class="number">4.0</span>],</span><br><span class="line">    [<span class="string">r'-1.0'</span>, <span class="string">r'0.0'</span>, <span class="string">r'1.0'</span>, <span class="string">r'2.0'</span>, <span class="string">r'3.0'</span>, <span class="string">r'4.0'</span>])</span><br></pre></td></tr></table></figure>
<p>可通过如下代码，设置 X、Y 坐标轴和标题：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 设置标题、x轴、y轴</span></span><br><span class="line">plt.title(<span class="string">r'$the \ function \ figure \ of \ cos(), \ sin() \ and \ sqrt()$'</span>, fontsize=<span class="number">19</span>)</span><br><span class="line">plt.xlabel(<span class="string">r'$the \ input \ value \ of \ x$'</span>, fontsize=<span class="number">18</span>, labelpad=<span class="number">88.8</span>)</span><br><span class="line">plt.ylabel(<span class="string">r'$y = f(x)$'</span>, fontsize=<span class="number">18</span>, labelpad=<span class="number">12.5</span>)</span><br></pre></td></tr></table></figure>
<h3 id="设置文字描述、注解"><a href="#设置文字描述、注解" class="headerlink" title="设置文字描述、注解"></a>设置文字描述、注解</h3><p>可通过如下代码，在数据图中添加文字描述 <strong>text</strong>：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">plt.text(<span class="number">4</span>, <span class="number">1.68</span>, <span class="string">r'$x \in [0.0, \ 10.0]$'</span>, color=<span class="string">'k'</span>, fontsize=<span class="number">15</span>)</span><br><span class="line">plt.text(<span class="number">4</span>, <span class="number">1.38</span>, <span class="string">r'$y \in [-1.0, \ 4.0]$'</span>, color=<span class="string">'k'</span>, fontsize=<span class="number">15</span>)</span><br></pre></td></tr></table></figure>
<p>// 其中，r’$…$’ 语句表示使用 <strong>LaTex</strong> 公式符号，LaTex 公式符号见参考文献 [5].</p>
<p>可通过如下代码，在数据图中给特殊点添加注解 <strong>annotate</strong>：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 特殊点添加注解</span></span><br><span class="line">plt.scatter([<span class="number">8</span>,],[np.sqrt(<span class="number">8</span>),], <span class="number">50</span>, color =<span class="string">'m'</span>)  <span class="comment"># 使用散点图放大当前点</span></span><br><span class="line"></span><br><span class="line">plt.annotate(<span class="string">r'$2\sqrt&#123;2&#125;$'</span>, xy=(<span class="number">8</span>, np.sqrt(<span class="number">8</span>)), xytext=(<span class="number">8.5</span>, <span class="number">2.2</span>), fontsize=<span class="number">16</span>, color=<span class="string">'#090909'</span>, arrowprops=dict(arrowstyle=<span class="string">'-&gt;'</span>, connectionstyle=<span class="string">'arc3, rad=0.1'</span>, color=<span class="string">'#090909'</span>))</span><br></pre></td></tr></table></figure>
<h3 id="设置图例"><a href="#设置图例" class="headerlink" title="设置图例"></a>设置图例</h3><p>可使用如下两种方式，给绘图设置图例：<br>1: 在 <strong>plt.plot</strong> 函数中添加 <strong>label</strong> 参数后，使用 plt.legend(loc=’up right’)<br>2: 不使用参数 label, 直接使用如下命令：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">plt.legend([<span class="string">'cos(x)'</span>, <span class="string">'sin(x)'</span>, <span class="string">'sqrt(x)'</span>], loc=<span class="string">'up right'</span>)</span><br></pre></td></tr></table></figure>
<p><strong>loc</strong> 参数表示图例的位置，常见的位置参数如下：</p>
<p><img src="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/legend.png" alt="legend loc 参数"></p>
<p>legend loc 参数图片由参考文献 [2] 提供。</p>
<h3 id="网格线开关"><a href="#网格线开关" class="headerlink" title="网格线开关"></a>网格线开关</h3><p>可使用如下代码，给绘图设置网格线：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 显示网格线</span></span><br><span class="line">plt.grid(<span class="keyword">True</span>)</span><br></pre></td></tr></table></figure>
<h3 id="显示、保存"><a href="#显示、保存" class="headerlink" title="显示、保存"></a>显示、保存</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">plt.show()    <span class="comment"># 显示</span></span><br><span class="line"><span class="comment"># savefig('../figures/plot3d_ex.png',dpi=48)    # 保存，前提目录存在</span></span><br></pre></td></tr></table></figure>
<p>本例完整代码已上传 github:</p>
<p><a href="https://github.com/absentm/Demo/blob/master/pythonCode/plot.py" target="_blank" rel="noopener">plot.py</a></p>
<h3 id="显示中文"><a href="#显示中文" class="headerlink" title="显示中文"></a>显示中文</h3><p>默认的编程环境无法显示中文字符，这里提供一种方法，添加如下配置代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">plt.rcParams[<span class="string">'font.sans-serif'</span>]=[<span class="string">'SimHei'</span>]    <span class="comment"># 用来正常显示中文标签</span></span><br><span class="line">plt.rcParams[<span class="string">'axes.unicode_minus'</span>]=<span class="keyword">False</span>      <span class="comment"># 用来正常显示负号</span></span><br></pre></td></tr></table></figure>
<hr>
<h2 id="其他图画法"><a href="#其他图画法" class="headerlink" title="其他图画法"></a>其他图画法</h2><p>按照类型图的分类，下文简要记录一下直方图的基础代码，其他，如散点图、饼状图、轮廓图、3D图、多子图等从参考文献 [1] 获取。</p>
<h3 id="直方图"><a href="#直方图" class="headerlink" title="直方图"></a>直方图</h3><p>直方图，也即柱状图，使用 bar API 进行绘制</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#coding:utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"><span class="keyword">from</span> pylab <span class="keyword">import</span> *</span><br><span class="line"></span><br><span class="line">x_size = [<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">9</span>, <span class="number">11</span>, <span class="number">13</span>]</span><br><span class="line">y_time_point = [<span class="number">0</span>, <span class="number">200</span>, <span class="number">415</span>, <span class="number">628</span>, <span class="number">714</span>, <span class="number">862</span>, <span class="number">0</span>]</span><br><span class="line"></span><br><span class="line">x_zhe = [<span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">9</span>, <span class="number">11</span>]</span><br><span class="line">y_zhe = [<span class="number">200</span>, <span class="number">415</span>, <span class="number">628</span>, <span class="number">714</span>, <span class="number">862</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 设置刻度标签</span></span><br><span class="line">plt.xticks(x_zhe, (<span class="string">u"3"</span>, <span class="string">u"5"</span>, <span class="string">u"7"</span>, <span class="string">u"9"</span>, <span class="string">u"11"</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 绘制柱状图</span></span><br><span class="line">plt.bar(left = (x_size), height = (y_time_point), width = <span class="number">1.0</span>,</span><br><span class="line">	align=<span class="string">"center"</span>, facecolor = <span class="string">'lightskyblue'</span>,edgecolor = <span class="string">'white'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 添加文本解释</span></span><br><span class="line"><span class="keyword">for</span> x, y <span class="keyword">in</span> zip(x_zhe, y_zhe):</span><br><span class="line">    plt.text(x, y+<span class="number">10</span>, <span class="string">'%.0f'</span> % y, ha=<span class="string">'center'</span>, va= <span class="string">'bottom'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">#设置y轴范围</span></span><br><span class="line">ylim(<span class="number">0</span>, <span class="number">1000</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 画折线图</span></span><br><span class="line">plt.plot(x_zhe, y_zhe, <span class="string">'y.-'</span>)</span><br><span class="line">plt.title(<span class="string">'Time values change with Size'</span>)</span><br><span class="line">plt.xlabel(<span class="string">'Size'</span>)</span><br><span class="line">plt.ylabel(<span class="string">'Time (s)'</span>)</span><br><span class="line">plt.grid(<span class="keyword">True</span>)</span><br><span class="line">plt.show()</span><br></pre></td></tr></table></figure>
<p>以上代码可以得到如下直方图：</p>
<p><img src="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/bar.png" alt="直方图"></p>
<h2 id="参考文献"><a href="#参考文献" class="headerlink" title="参考文献"></a>参考文献</h2><p>[1] <a href="http://www.labri.fr/perso/nrougier/teaching/matplotlib/#beyond-this-tutorial" target="_blank" rel="noopener">http://www.labri.fr/perso/nrougier/teaching/matplotlib/#beyond-this-tutorial</a><br>[2] <a href="http://www.bioinfo.org.cn/~casp/temp/spring.lecture/Matplotlib_slides.pdf" target="_blank" rel="noopener">http://www.bioinfo.org.cn/~casp/temp/spring.lecture/Matplotlib_slides.pdf</a><br>[3] <a href="http://matplotlib.org/api/pyplot_api.html" target="_blank" rel="noopener">http://matplotlib.org/api/pyplot_api.html</a><br>[4] <a href="http://python.jobbole.com/85106/" target="_blank" rel="noopener">http://python.jobbole.com/85106/</a><br>[5] <a href="http://mohu.org/info/symbols/symbols.htm" target="_blank" rel="noopener">http://mohu.org/info/symbols/symbols.htm</a></p>
<hr>
<h2 id="声明"><a href="#声明" class="headerlink" title="声明"></a>声明</h2><blockquote>
<p>转载请注明作者和出处，禁止一切商业用途！</p>
</blockquote>
<h2 id="END"><a href="#END" class="headerlink" title="END"></a>END</h2><hr>
      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center">
  <div>Enjoy it ? Donate me !  求鼓励，求支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>Donate</span>
  </button>
  <div id="QR" style="display: none">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/wechat.png" alt="AbsentM WeChat Pay">
        <p>WeChat Pay</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/alipay.png" alt="AbsentM Alipay">
        <p>Alipay</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/01/16/常用的-Shell-命令整理/" rel="next" title="常用的 Shell 命令整理">
                <i class="fa fa-chevron-left"></i> 常用的 Shell 命令整理
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/11/21/Eclipse-优化配置项说明/" rel="prev" title="Eclipse 优化配置项说明">
                Eclipse 优化配置项说明 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="https://raw.githubusercontent.com/absentm/gitRes/master/NotePics/googlrPhoto.png" alt="AbsentM">
            
              <p class="site-author-name" itemprop="name">AbsentM</p>
              <p class="site-description motion-element" itemprop="description">Avenue to Jane!</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">57</span>
                    <span class="site-state-item-name">posts</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">8</span>
                    <span class="site-state-item-name">categories</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">37</span>
                    <span class="site-state-item-name">tags</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/absentm" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://twitter.com/absentm123" target="_blank" title="Twitter"><i class="fa fa-fw fa-twitter"></i>Twitter</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://weibo.com/dmicrocosmos" target="_blank" title="Weibo"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
                  
                </span>
              
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.hanhanfilm.com/" title="憨憨电影" target="_blank">憨憨电影</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.fengxiaochuang.com/" title="晓闯博客" target="_blank">晓闯博客</a>
                  </li>
                
              </ul>
            </div>
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#引言"><span class="nav-number">1.</span> <span class="nav-text">引言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#matplotlib-安装配置"><span class="nav-number">2.</span> <span class="nav-text">matplotlib 安装配置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#图的基本结构"><span class="nav-number">3.</span> <span class="nav-text">图的基本结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#绘图分类"><span class="nav-number">4.</span> <span class="nav-text">绘图分类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#画法"><span class="nav-number">5.</span> <span class="nav-text">画法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#导包"><span class="nav-number">5.1.</span> <span class="nav-text">导包</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#准备数据"><span class="nav-number">5.2.</span> <span class="nav-text">准备数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#绘制基本曲线"><span class="nav-number">5.3.</span> <span class="nav-text">绘制基本曲线</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#设置坐标轴"><span class="nav-number">5.4.</span> <span class="nav-text">设置坐标轴</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#设置文字描述、注解"><span class="nav-number">5.5.</span> <span class="nav-text">设置文字描述、注解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#设置图例"><span class="nav-number">5.6.</span> <span class="nav-text">设置图例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#网格线开关"><span class="nav-number">5.7.</span> <span class="nav-text">网格线开关</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#显示、保存"><span class="nav-number">5.8.</span> <span class="nav-text">显示、保存</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#显示中文"><span class="nav-number">5.9.</span> <span class="nav-text">显示中文</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#其他图画法"><span class="nav-number">6.</span> <span class="nav-text">其他图画法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#直方图"><span class="nav-number">6.1.</span> <span class="nav-text">直方图</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考文献"><span class="nav-number">7.</span> <span class="nav-text">参考文献</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#声明"><span class="nav-number">8.</span> <span class="nav-text">声明</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#END"><span class="nav-number">9.</span> <span class="nav-text">END</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">AbsentM</span>

  

  
</div>




  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme – <a class="theme-link" target="_blank" href="https://theme-next.org">NexT.Mist</a> v6.3.0</div>
        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="Total Visitors">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="Total Views">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    
	
    

    
      <div>
        <!-- Go to www.addthis.com/dashboard to customize your tools -->
<div class="addthis_inline_share_toolbox">
  <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-58d66725c4aec37d" async="async"></script>
</div>

      </div>
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























  



  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/reading_progress/reading_progress.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.3.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.3.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.3.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.3.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.3.0"></script>



  

  
    <script id="dsq-count-scr" src="https://absentm.disqus.com/count.js" async></script>
  

  
    <script type="text/javascript">
      var disqus_config = function () {
        this.page.url = 'https://absentm.github.io/2017/03/18/Python-matplotlib-数据可视化/';
        this.page.identifier = '2017/03/18/Python-matplotlib-数据可视化/';
        this.page.title = 'Python matplotlib 数据可视化';
        };
      function loadComments () {
        var d = document, s = d.createElement('script');
        s.src = 'https://absentm.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      }
      
        $(function () {
          var offsetTop = $('#comments').offset().top - $(window).height();
          if (offsetTop <= 0) {
            // load directly when there's no a scrollbar
            loadComments();
          } else {
            $(window).on('scroll.disqus_scroll', function () {
              var scrollTop = document.documentElement.scrollTop;
              if (scrollTop >= offsetTop) {
                $(window).off('.disqus_scroll');
                loadComments();
              }
            });
          }
        });
      
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("8gIMbJWMH7XprqgkEiPWXvuu-gzGzoHsz", "W9NRpyhllWph45XiJsEHVgct");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            
            counter.save(null, {
              success: function(counter) {
                
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(counter.get('time'));
                
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            
              var newcounter = new Counter();
              /* Set ACL */
              var acl = new AV.ACL();
              acl.setPublicReadAccess(true);
              acl.setPublicWriteAccess(true);
              newcounter.setACL(acl);
              /* End Set ACL */
              newcounter.set("title", title);
              newcounter.set("url", url);
              newcounter.set("time", 1);
              newcounter.save(null, {
                success: function(newcounter) {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
                },
                error: function(newcounter, error) {
                  console.log('Failed to create');
                }
              });
            
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  

  


  
  

  

  

  

  

  

</body>
</html>